<template>
  <a-modal
    title="操作"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="公司"
        >
          <a-select
            @change="onchange"
            v-decorator="[ 'companyId', {rules: [{ required: true, message: '请选择。。。' }], initialValue: defaultCompany} ]">
            <a-select-option v-for="item in companys" :key="item.id">{{item.name}}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="活动名称"
        >
          <a-input placeholder="活动名称"
                   v-decorator="[ 'name', {rules: [{ required: true, message: '请输入。。。' }]} ]"/>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="有效时间" >
          <a-range-picker @change="onDateChange" style="width: 100%"
                          :format="dateFormat"
                          :showTime="{format:'HH:mm'}"
                          v-decorator="[ 'validTime', {rules: [{ required: true, message: '请选择时间' }]}]"
          />
        </a-form-item>

        <a-divider/>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="商品配置"
        >
          <a-select mode="multiple"
                    v-decorator="[ 'productIds', {rules: [],initialValue:defaultProductIds} ]">
            <a-select-option v-for="item in productIds" :key="item.id">{{item.name}}({{item.id}})</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>

  import { addOrUpdate,selectActivityProductByCompanyId } from '@/api/market/activityproduct'
  import { selectAll } from '@/api/companyService/company'
  import {selectProductListByCompanyId} from '@/api/productService/product'
  import pick from 'lodash.pick'
  import moment from 'moment';

  export default {
    //--############  data() ###############-->
    data() {
      return {
        dateFormat: 'YYYY-MM-DD HH:mm',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        visible: false,
        confirmLoading: false,
        mdl: {},
        form: this.$form.createForm(this),

        isDisabled: false,
        productIds: [],
        defaultProductIds:[],
        companys:[],
        roles: [],
        defaultCompany: '',
        validTime:[],
        company:{}
      }
    },
    //--############  data() ###############-->

    created() {
      selectAll().then(res => {
        this.companys = res.result
        this.defaultCompany = this.companys[0].id
      })

    },

    //--############  methods() ###############-->
    methods: {
      onchange(e){
        this.company={
          "companyId":e
        }
        selectProductListByCompanyId(this.company).then(res =>{
          this.productIds = res.result;
        })
        this.defaultCompany = e;
        this.defaultProductIds=[]
      },
      onDateChange(e){
        if(e.length == 0){
          this.company={
            "companyId":this.defaultCompany
          }
        }else{
          let beginDate = e[0].format('YYYY-MM-DD HH:mm')+":00"
          let endDate = e[1].format('YYYY-MM-DD HH:mm')+":59"
          console.log('endDate',endDate)
          this.company={
            "companyId":this.defaultCompany,
            "beginTime":beginDate,
            "endTime":endDate
          }
        }
        selectProductListByCompanyId(this.company).then(res =>{
          this.productIds = res.result;
        })
      },
      add() {
        this.isDisabled = false
        this.visible = true
        this.form.resetFields()
        this.mdl = {}
        this.defaultProductIds = []
      },
      edit(record) {
        this.company={
          "companyId":record.companyId
        }
        selectProductListByCompanyId(this.company).then(res =>{
          this.productIds = res.result;
          selectActivityProductByCompanyId(record.id).then(res =>{
            this.defaultProductIds = res.result;
          })
        })
        this.isDisabled = true
        this.visible = true
        this.validTime.push(moment(record.beginTime))
        this.validTime.push(moment(record.endTime))

        record.validTime = this.validTime
        this.mdl = Object.assign({}, record)
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(record, 'name', 'companyId','validTime'))
        })

      },
      close() {
        this.$emit('close')
        this.visible = false
        this.form.resetFields()
        this.mdl={}
        this.validTime = []
      },
      handleOk() {
        const _this = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          // 验证表单没错误
          if (!err) {
            values.id = this.mdl.id;
            _this.confirmLoading = true
            // 模拟后端请求 2000 毫秒延迟 " 00:00:00" +" 23:59:59"
            values.beginTime = values.validTime[0].format('YYYY-MM-DD HH:mm:ss')+":00"
            values.endTime = values.validTime[1].format('YYYY-MM-DD HH:mm:ss')+":00"
            addOrUpdate(values).then((res) => {
              if (res.code === 200) {
                _this.$message.success('保存成功')
                _this.$emit('ok')
                _this.close()
              }else {
                this.$notification.error({
                  message: '错误',
                  description: res.message,
                  duration: 4
                })
              }
            }).catch(() => {
              // Do something
            }).finally(() => {
              _this.confirmLoading = false
            })
          }
        })
      },
      handleCancel() {
        this.close()
      },
    }
    //--############  methods() ###############-->
  }
</script>

<style scoped>

</style>
